#include "effecteditwidget.h"
#include "ui_effecteditwidget.h"
#include "eventcenter.h"
#include <QDebug>
#include <QDragEnterEvent>
#include "ResourceManger/resourcelistwidget.h"
#include "ResourceManger/filemanager.h"
#include "GameData/jsontranslator.h"
EffectEditWidget::EffectEditWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EffectEditWidget)
{
    ui->setupUi(this);
    this->setWindowIcon(QIcon(":res/icon/effectIcon.png"));
    this->setWindowFlags(Qt::WindowStaysOnTopHint);
    this->setWindowTitle("编辑粒子系统");
    this->resize(800,600);
    this->setAcceptDrops(true);
    InitEffectListUI();
    InitTextureListUI();
    connect(&EventCenter::Instance(),&EventCenter::RenderInitOver,this,[=](){
        InitDefaultEffect();
    });
}

EffectEditWidget::~EffectEditWidget()
{
    delete ui;
}

void EffectEditWidget::SendInfo(QString name)
{
    if(name.isEmpty())
    {
        emit EventCenter::Instance().ChangeParticleSystem(nullptr);
        return;
    }
    ParticleSystemInfo* info = infos[name];
    emit EventCenter::Instance().ChangeParticleSystem(info);
}

void EffectEditWidget::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction();
}

void EffectEditWidget::dropEvent(QDropEvent *event)
{
    ResourceListWidget * w = dynamic_cast<ResourceListWidget*>(event->source());
    if(!w) return;
    QString path = w->GetCurItemPath();
    QDir d;
    path = d.relativeFilePath(path);
    if(FileManager::Instance().GetFileType(path) != FileManager::IMAGE)
        return;
    QString name = QFileInfo(path).fileName();
    emit EventCenter::Instance().Modify();

    if(ui->addTexture->geometry().contains(this->mapFromGlobal(QCursor::pos())))
    {
        AddTexture(path);
    }
}

void EffectEditWidget::InitDefaultEffect()
{
    ParticleSystemInfo* info0 = new ParticleSystemInfo();
    info0->name = "雨";
    info0->SetARange(0,-0.001,0,0);
    info0->SetARange(0,-0.001,0,0);
    info0->SetSizeRange(0.01,0.04,0.04,0.08);
    info0->SetVRange(0,-0.04,0,-0.02);
    info0->SetInitPosRange(-1,-1,1,1.1);
    info0->lockScale = false;
    info0->maxCount = 300;
    info0->AddTexture(":/res/texture/rain.png");

    ParticleSystemInfo* info1 = new ParticleSystemInfo();
    info1->name = "雪";
    info1->SetARange(0,-0.0001,0,0);
    info1->SetSizeRange(0.01,0.03,0.01,0.03);
    info1->SetVRange(0,-0.004,0,-0.002);
    info1->SetInitPosRange(-1,-1,1,1.1);
    info1->maxCount = 80;
    info1->AddTexture(":/res/texture/snow.png");

    whiteList.push_back("雨");
    whiteList.push_back("雪");

    infos.insert(info0->name,info0);
    infos.insert(info1->name,info1);

    for(int i = 0;i < whiteList.count();i++)
    {
        ui->EffectListWidget->addItem(whiteList[i]);
    }
    ui->EffectListWidget->setCurrentRow(0);

    //读取用户自定义的特效
    JsonTranslator jt;
    QJsonObject* ob = FileManager::Instance().ReadJsonFile(FileManager::Instance().effectPath);
    if(!ob)
    {
        return;
    }
    QJsonArray a = (*ob)["effect"].toArray();
    for(int i = 0;i < a.count();i++)
    {
        QJsonObject eOb = a[i].toObject();
        ParticleSystemInfo* info = jt.ParticleInfoFromJson(&eOb);
        if(info)
        {
            ui->EffectListWidget->addItem(info->name);
            infos.insert(info->name,info);
            emit EventCenter::Instance().AddEffect(info->name);
        }
    }
    delete ob;
    ob = nullptr;
}

void EffectEditWidget::InitEffectListUI()
{
    connect(ui->AddEffectBtn,&QPushButton::clicked,this,[=](){AddEffect();});
    connect(ui->DeleteEffectBtn,&QPushButton::clicked,this,[=](){
        if(ui->EffectListWidget->count() <= 0 || ui->EffectListWidget->currentRow() < 0)
            return;
        DeleteEffect(ui->EffectListWidget->currentItem()->text());
    });
    connect(ui->EffectListWidget,&QListWidget::currentRowChanged,this,[=](int row){
        LoadEffect(row);
    });
}

void EffectEditWidget::InitTextureListUI()
{
    QSize iconSize = QSize(150,150);
    ui->TextureListWidget->setIconSize(iconSize);
    ui->TextureListWidget->setViewMode(QListView::IconMode);
    ui->TextureListWidget->setFlow(QListView::LeftToRight);
    ui->TextureListWidget->setResizeMode(QListView::Adjust);
    ui->TextureListWidget->setMovement(QListView::Static);
    //保存按钮
    connect(ui->saveBtn,&QPushButton::clicked,this,[=](){Save();});
    //删除纹理按钮
    connect(ui->DeleteTextureBtn,&QPushButton::clicked,[=](){
        if(ui->TextureListWidget->count() <= 0)
            return;
        DeleteTexture();
    });
}

void EffectEditWidget::AddEffect(ParticleSystemInfo *info)
{
    if(!info)
    {
        info = new ParticleSystemInfo();
        info->name = "效果" + QString::number(nameId);
        nameId++;
    }
    infos.insert(info->name,info);
    QListWidgetItem* item = new QListWidgetItem();
    ui->EffectListWidget->addItem(item);
    ui->EffectListWidget->setCurrentItem(item);
    item->setText(info->name);
    emit EventCenter::Instance().AddEffect(info->name);
    LoadEffect(ui->EffectListWidget->currentRow());
}

void EffectEditWidget::DeleteEffect(QString name)
{
    if(whiteList.contains(name))
        return;

    ParticleSystemInfo* info = infos[name];
    infos.remove(name);
    if(info)
    {
        delete info;
        info = nullptr;
    }

    for(int i = 0;i < ui->EffectListWidget->count();i++)
    {
        if(ui->EffectListWidget->item(i)->text() == name)
        {
            if(i == 0)
                ui->EffectListWidget->setCurrentRow(1);
            else
                ui->EffectListWidget->setCurrentRow(i - 1);
            ui->EffectListWidget->takeItem(i);
            break;
        }
    }
    emit EventCenter::Instance().DeleteEffect(name);
}

void EffectEditWidget::LoadEffect(int row)
{
    if(row < 0 || row >= ui->EffectListWidget->count())
        return;

    QString name = ui->EffectListWidget->item(row)->text();
    ParticleSystemInfo* info = infos[name];
    if(!info)
        return;

    ui->radioButton->setChecked(info->lockScale);
    ui->nameLineEdit->setText(info->name);
    ui->MaxCount->setValue(info->maxCount);

    ui->minx0->setValue(info->min_x0);
    ui->maxx0->setValue(info->max_x0);
    ui->miny0->setValue(info->min_y0);
    ui->maxy0->setValue(info->max_y0);

    ui->minxv->setValue(info->min_xv);
    ui->maxxv->setValue(info->max_xv);
    ui->minyv->setValue(info->min_yv);
    ui->maxyv->setValue(info->max_yv);

    ui->minxa->setValue(info->min_xa);
    ui->maxxa->setValue(info->max_xa);
    ui->minya->setValue(info->min_ya);
    ui->maxya->setValue(info->max_ya);

    ui->minxs->setValue(info->min_xsize);
    ui->maxxs->setValue(info->max_xsize);
    ui->minys->setValue(info->min_ysize);
    ui->maxys->setValue(info->max_ysize);
    LoadTexture();
}

void EffectEditWidget::AddTexture(QString path)
{
    QString name = ui->EffectListWidget->currentItem()->text();
    ParticleSystemInfo* info = infos[name];

    if(!info)
        return;
    info->AddTexture(path);

    LoadTexture();
}

void EffectEditWidget::DeleteTexture()
{
    int row = ui->TextureListWidget->currentRow();
    if(row == 0)
        ui->TextureListWidget->setCurrentRow(row + 1);
    else
        ui->TextureListWidget->setCurrentRow(row - 1);
    ui->TextureListWidget->takeItem(row);
    QString name = ui->EffectListWidget->currentItem()->text();
    ParticleSystemInfo* info = infos[name];
    if(!info)
        return;
    info->DeleteTexture(row);
}

void EffectEditWidget::LoadTexture()
{
    QString name = ui->EffectListWidget->currentItem()->text();
    ParticleSystemInfo* info = infos[name];
    if(!info)
        return;
    int count = info->TextureCount();
    QSize itemSize = QSize(150,150);
    ui->TextureListWidget->clear();
    for(int i = 0;i < count;i++)
    {
        QListWidgetItem* item = new QListWidgetItem(QIcon(QPixmap(info->GetPath(i))),"");
        item->setSizeHint(itemSize);
        ui->TextureListWidget->addItem(item);
    }
}

void EffectEditWidget::Save()
{
    //保存编辑好的数据
    QString name = ui->EffectListWidget->currentItem()->text();

    ParticleSystemInfo* info = infos[name];
    if(!info)
        return;

    QString newName = ui->nameLineEdit->text();
    if(!(infos.contains(newName) && infos[newName]))
    {
        info->name = newName;
        infos.remove(name);
        infos.insert(info->name,info);
    }
    ui->EffectListWidget->currentItem()->setText(info->name);
    info->SetARange(ui->minxa->value(),ui->minya->value(),ui->maxxa->value(),ui->maxya->value());
    info->SetSizeRange(ui->minxs->value(),ui->maxxs->value(),ui->minys->value(),ui->maxys->value());
    info->SetVRange(ui->minxv->value(),ui->minyv->value(),ui->maxxv->value(),ui->maxyv->value());
    info->SetInitPosRange(ui->minx0->value(),ui->miny0->value(),ui->maxx0->value(),ui->maxy0->value());
    info->lockScale = ui->radioButton->isChecked();
    info->maxCount = ui->MaxCount->value();
    emit EventCenter::Instance().DeleteEffect(name);
    emit EventCenter::Instance().AddEffect(newName);

    //数据持久化
    JsonTranslator jt;
    QJsonObject* ob = new QJsonObject();
    QJsonArray a;
    //用于清理内存
    QVector<QJsonObject*> rubbish;
    for(auto it = infos.begin();it != infos.end();it++)
    {
        if(!it.value() || whiteList.contains(it.key()))
            continue;
        QJsonObject* eOb = jt.ToJson(it.value());
        a.append(*eOb);
        rubbish.push_back(eOb);
    }
    ob->insert("effect",a);
    FileManager::Instance().Write(FileManager::Instance().effectPath,jt.Json2Byte(ob));

    //清理内存
    delete ob;
    ob = nullptr;
    for(int i = 0;i < rubbish.count();i++)
    {
        QJsonObject* ob = rubbish[i];
        rubbish[i] = nullptr;
        delete ob;
        ob = nullptr;
    }
    rubbish.clear();
}
